import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot } from '@angular/router';
import { ApiService } from '../../../../providers/ApiPro.service';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd';


@Component({
  selector: 'app-SetUserDia',
  templateUrl: './SetUserDia.component.html',
  styleUrls: ['./SetUserDia.component.scss']
})
export class SetUserDiaComponent implements OnInit {
  public validateForm: FormGroup;
  public isVisible = true;
  public isConfirmLoading = false;
  public isEdit: boolean;
  public isError: boolean = false;
  public optionPostion: any;


  constructor(
      public router: Router,
      private fb: FormBuilder,
      private apiservice: ApiService,
      private route: ActivatedRoute,
      private confirmServ: NzModalService
      
  ) { }

  ngOnInit() {
    this.getId();
    this.getPostion();
  }

   getId(){
     this.route.params.subscribe((params) => {
            if(params['id']){
              this.load(params['id']);              
              this.isEdit = true;
            }// 通过这个方法来判断是否为审核
            else{
              this.initForm();
            }
        });
   }

  initForm(){
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      // mobile: [ null, [ Validators.required ] ],
      positionId: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required , this.pwValidator ] ],
      accountNo: [ null, [ Validators.required,this.anValidator ] ],
    });
  }


  anValidator = (control: FormControl): { [s: string]: boolean } => {
    const pw_REGEXP = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!control.value) {
      return { required: true }
    } else if (!pw_REGEXP.test(control.value)) {
      return { error: true, accountNo: true };
    }
  };

  getPostion(){
    let url = "findallpositions";
    this.apiservice.get(url)
      .then(res =>{
        this.optionPostion = res.result;
      })    
  }


  load(id){
    this.initForm();
    let url = "finduserdetail"
    this.apiservice.get(url,{"userId":id})
      .then(res =>{
      console.log(res);
       this.validateForm = this.fb.group({
          userName: [ res.result.userName, [ Validators.required ] ],
          // mobile: [ res.result.mobile, [ Validators.required ] ],
          positionName: [ res.result.positionName, ],
          password: [ res.result.password, [ Validators.required, this.pwValidator ]],
          accountNo: [ res.result.accountNo, [ Validators.required, this.anValidator ] ],
          userId : [ res.result.userId , ],
          positionId : [ res.result.positionId ,[ Validators.required ]  ],
        });
      })
  }

  showModal = () => {
    this.isVisible = true;
  }

  handleOk () {
    this.isConfirmLoading = true;
    this._submitForm();
    if(this.isError){
        setTimeout(() => {
          this.isConfirmLoading = false;
          this.isError = false;
        }, 1500);
    }else{
       setTimeout(() => {
          this.isVisible = false;
          this.isConfirmLoading = false;
          this.router.navigateByUrl("layout/set/user");
        }, 300);
    }
  }

  handleCancel = (e) => {
    this.isVisible = false;
    this.router.navigateByUrl("layout/set/user");
  }


  _submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    if(this.validateForm.valid){
      this.createNew();
    }else{
      this.isError = true;
    }
  }

  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  createNew(){
    let url = "adduser";
    let urls = "edituser";
    if(this.isEdit){
      this.apiservice.post(urls,this.validateForm.value)
        .then( res =>{
          console.log(res);
        })
    }else{
      this.apiservice.post(url,this.validateForm.value)
        .then( res =>{
         if(res.result){
           this.success();
         }else{
          this.error(res.errMsg);
         }
      })
    }
  }

  pwValidator = (control: FormControl): { [s: string]: boolean } => {
    const pw_REGEXP = /^(?=.*[a-z,A-Z])(?=.*\d)[\s\S]{8,16}$/;
    if (!control.value) {
      return { required: true }
    } else if (!pw_REGEXP.test(control.value)) {
      return { error: true, password: true };
    }
  };

  error(err) {
    this.confirmServ.error({
      title: '错误',
      content: err,
      okText:'返回'
    });
  }

  success(){
    let self = this;
      this.confirmServ.success({
      title: '成功',
      content: '用户创建成功',
      okText:'确定',
      onOk() {
        self.router.navigateByUrl("layout/set/user");
      },
    });
  }
  

}
